<template>
    <div class="login-bg">
        <!-- 用户登录 -->
        <div class="login-card">
            <h2 class="login-title">智慧会议管理平台</h2>
            <div class="login-tabs">
                <div :class="['login-tab', activeTab === 'account' ? 'active' : '']" @click="activeTab = 'account'">
                    账号密码登录
                </div>
                <div :class="['login-tab', activeTab === 'phone' ? 'active' : '']" @click="activeTab = 'phone'">
                    手机号登录
                </div>
            </div>
            <el-form v-if="activeTab === 'account'" ref="ruleFormRef" :model="ruleForm" :rules="rules"
                label-width="auto" class="login-form">
                <el-form-item prop="userNumber">
                    <el-input v-model="ruleForm.userNumber" placeholder="账号" />
                </el-form-item>

                <el-form-item prop="userPassword">
                    <el-input v-model="ruleForm.userPassword" show-password placeholder="密码" />
                </el-form-item>

                <el-form-item>
                    <el-checkbox v-model="ruleForm.remember">记住密码</el-checkbox>
                    <a class="forgot-link" href="#">忘记密码</a>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)" class="login-btn">
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
            <el-form v-else ref="phoneFormRef" :model="phoneForm" :rules="phoneRules" label-width="auto"
                class="login-form">
                <el-form-item prop="phone">
                    <el-input v-model="phoneForm.phone" placeholder="手机号" maxlenth="11"/>
                </el-form-item>

                <el-form-item prop="code">
                    <el-input v-model="phoneForm.code" placeholder="验证码" style="width: 40%;" />
                    <img v-if="captchaImg && phoneForm.phone" :src="captchaImg"
                        style="height:32px;cursor:pointer;margin-left:10px;" title="点击刷新验证码" />
                    <el-button style="margin-left: 10px;" @click="handleGetCode">获取验证码</el-button>
                </el-form-item>

                <el-form-item>
                    <a class="forgot-link" href="#">忘记密码</a>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitPhoneForm(phoneFormRef)" class="login-btn">
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
            <div class="login-footer">
                <span>其他登录方式</span>
                <i class="iconfont icon-wechat"></i>
                <i class="iconfont icon-qq"></i>
                <i class="iconfont icon-weibo"></i>
                <a class="register-link" href="#">注册账户</a>
            </div>
        </div>
    </div>

</template>



<script lang="ts" setup>
import { reactive, ref,onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { pa } from 'element-plus/es/locales.mjs'
import { useUsereStore } from '../../stores/user'
import { GetCode, PhoneLogin, UserLogin } from '@/Api/user';

const userStore = useUsereStore();

const activeTab = ref<'account' | 'phone'>('account')

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "userNumber": "",
    "userPassword": "",
    "remember":false
})

const phoneFormRef = ref<FormInstance>()
const phoneForm = reactive({
    phone: '',
    code: ''
})

const router = useRouter()

const rules = reactive<FormRules>({
    userNumber: [
        { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    userPassword: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'change',
        },
    ],
})

const phoneRules = reactive<FormRules>({
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const response = await UserLogin(ruleForm)
            userStore.userInfo.idNumber = response.data.data.idNumber
            userStore.userInfo.userNumber = response.data.data.userNumber
            userStore.userInfo.jwt = response.data.data.jwt
            ElMessage.success("登录成功")
                                //登陆成功 勾选 记住密码
                                if (ruleForm.remember) {
                        localStorage.setItem("userNumber", ruleForm.userNumber);
                        localStorage.setItem("userPassword", ruleForm.userPassword);
                    }
                    else {
                        localStorage.removeItem("userNumber")
                        localStorage.removeItem("userPassword")
                    }
            router.push("/index")
        } else {
            console.log('error submit!', fields)
            ElMessage.error("登录失败")
        }
    })
}

const submitPhoneForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            const response = await PhoneLogin(phoneForm)
            userStore.userInfo.idNumber = response.data.data.idNumber
            userStore.userInfo.userNumber = response.data.data.userNumber
            userStore.userInfo.jwt = response.data.data.jwt
            ElMessage.success("登录成功")
            router.push("/index")
        } else {
            ElMessage.error("登录失败")
        }
    })
}

//接收验证码图片
const captchaImg = ref('')

// 获取验证码按钮点击
const handleGetCode = () => {
    if (!phoneForm.phone) {
        ElMessage.warning('请先输入手机号')
        captchaImg.value = ''
        return
    }
    getCode(phoneForm.phone)
}

// 获取验证码图片
const getCode = async (phone: any) => {
    // 调用封装的 GetCode 方法
    const response = await GetCode(phone)
    // 处理返回的 blob 数据
    captchaImg.value = URL.createObjectURL(response.data)
    ElMessage.success('成功获取验证码')
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

onMounted(() => {
    if (localStorage.getItem("userNumber")) {
        ruleForm.userNumber = localStorage.getItem("userNumber") ?? ""
        ruleForm.userPassword = localStorage.getItem("userPassword") ?? ""
        ruleForm.remember = true;
    }
})

</script>

<style scoped>
.login-bg {
    width: 100vw;
    height: 100vh;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: url('../../assets/images/(2).png');
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
}

.login-card {
    width: 420px;
    padding: 36px 32px 24px 32px;
    border-radius: 18px;
    background: rgba(255, 255, 255, 0.92);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.18);
    display: flex;
    flex-direction: column;
    align-items: center;
    border: none;
}

.login-title {
    text-align: center;
    color: #2d3a4b;
    font-size: 26px;
    font-weight: bold;
    margin-bottom: 28px;
    letter-spacing: 2px;
    text-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.login-tabs {
    display: flex;
    width: 100%;
    margin-bottom: 18px;
    border-bottom: 1.5px solid #e0e0e0;
}

.login-tab {
    flex: 1;
    text-align: center;
    padding: 10px 0;
    font-size: 16px;
    color: #888;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    transition: all 0.2s;
}

.login-tab.active {
    color: #409eff;
    font-weight: bold;
    border-bottom: 2px solid #409eff;
    background: #f7faff;
}

.login-form {
    width: 100%;
}

.el-form-item {
    margin-bottom: 22px;
}

.login-btn {
    width: 100%;
    font-size: 18px;
    letter-spacing: 2px;
    border-radius: 6px;
    padding: 10px 0;
}

.forgot-link {
    float: right;
    color: #409eff;
    font-size: 14px;
    text-decoration: none;
    margin-left: auto;
}

.login-footer {
    width: 100%;
    display: flex;
    align-items: center;
    margin-top: 18px;
    color: #888;
    font-size: 14px;
}

.login-footer .iconfont {
    margin: 0 8px;
    font-size: 20px;
    cursor: pointer;
}

.register-link {
    margin-left: auto;
    color: #409eff;
    text-decoration: none;
}
</style>